package com.webwork.mood.record.controller;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.webwork.mood.common.controller.SuperCtrl;
import com.webwork.mood.record.dataobject.FeedbackView;
import com.webwork.mood.record.dataobject.LevelScore;
import com.webwork.mood.record.dataobject.MoodFeedback;
import com.webwork.mood.record.dataobject.MoodRecord;
import com.webwork.mood.record.dataobject.ScoreReason;
import com.webwork.mood.record.service.DrawRecordService;
import com.webwork.mood.record.service.LevelService;
import com.webwork.mood.record.service.MoodService;
import com.webwork.mood.system.dataobject.User;
import com.webwork.mood.system.service.UserService;
import com.webwork.mood.util.DateFormat;
import com.webwork.mood.util.StrManager;

@Controller
public class MoodController extends SuperCtrl {

	@Autowired
	private UserService userSve;
	
	@Autowired
	private MoodService moodSve;
	
	@Autowired
	private LevelService levelSve;
	
	@Autowired
	private DrawRecordService drawRecordSve;
	
	@RequestMapping(value = "/moodIndex")
	@Override
	public String mainPage() {
		return "mood";
	}
	
	@RequestMapping(value = "/submitMood")
	@ResponseBody
	public ResponseEntity<String> submitMood(@RequestParam("mood") int mood,
			@RequestParam("telephone") String telephone) {
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		FeedbackView view = new FeedbackView();
		
		User queryObj = new User();
		queryObj.setTelephone(telephone);
		List<User> list = userSve.query(queryObj);
		if (list == null || list.size() == 0) {
			view.setResult("noExist");
			view.setScore(mood);
			return new ResponseEntity<String>(new Gson().toJson(view).toString(), responseHeaders, HttpStatus.CREATED);
		}
		User user = list.get(0);

		String nowDate = DateFormat.SHORT_NUMBER.format(new Date());
		MoodRecord recordQuery = new MoodRecord();
		recordQuery.setRecordId("MR" + nowDate);
		recordQuery.setUserId(user.getUserId());
		List<MoodRecord> records = moodSve.query(recordQuery);
		if (records != null && records.size() > 0) {
			view.setResult("exists");
			view.setScore(mood);
			return new ResponseEntity<String>(new Gson().toJson(view).toString(), responseHeaders, HttpStatus.CREATED);
		}
		
		MoodRecord record = new MoodRecord();
		record.setRecordId("MR" + DateFormat.NUMBER.format(new Date()));
		record.setUserId(user.getUserId());
		record.setScore(mood);
		record.setRecordDate(new Date());
		moodSve.insert(record);
		view.setResult("success");
		view.setScore(mood);
		
		recordQuery = new MoodRecord();
		recordQuery.setRecordId("MR" + nowDate);
		records = moodSve.query(recordQuery);
		int total = 0;
		int i = 0;
		Collections.sort(records, new Comparator<MoodRecord>() {
			public int compare(MoodRecord arg0, MoodRecord arg1) {
				return Integer.valueOf(arg0.getScore()).compareTo(Integer.valueOf(arg1.getScore()));
			}
		});
		for (MoodRecord mr : records) {
			total += mr.getScore();
			i++;
			if (mr.getUserId().equals(user.getUserId())) {
				view.setRank(i);
			}
		}
		if (total == 0 || records.size() == 0) {
			view.setAverage(0);
		} else {
			view.setAverage(Double.valueOf(total) / Double.valueOf(records.size()));
		}
		return new ResponseEntity<String>(new Gson().toJson(view).toString(), responseHeaders, HttpStatus.CREATED);
	}
	
	@RequestMapping(value = "/submitMoodScore", produces = "text/html;charset=UTF-8") //避免json中文?乱码
	@ResponseBody
	public String submitMoodScore(
			@RequestParam("score") int score,
			@RequestParam("reason") String reason,
			@RequestParam("weixinId") String weixinId,
			HttpServletResponse response) {
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		String nowDate = DateFormat.SHORT_NUMBER.format(new Date());
		MoodFeedback mf = new MoodFeedback();
		
		String userId = "";
		User userQuery = new User();
		userQuery.setWeixinId(weixinId);
		List<User> users = userSve.query(userQuery);
		if (users != null && users.size() > 0) {
			userId = users.get(0).getUserId();
		}
		
		MoodRecord recordQuery = new MoodRecord();
		recordQuery.setRecordId("MR" + nowDate);
		recordQuery.setWeixinId(weixinId);
		List<MoodRecord> records = moodSve.query(recordQuery);
		if (records != null && records.size() > 0) {
			mf.setStatus(2);
			score = records.get(0).getScore();
		} else {
			
			MoodRecord record = new MoodRecord();
			record.setRecordId("MR" + DateFormat.NUMBER.format(new Date()));
			if (!StrManager.isEmpty(userId)) {
				record.setUserId(userId);
			}
			record.setWeixinId(weixinId);
			record.setScore(score);
			record.setComment(reason);
			record.setRecordDate(new Date());
			moodSve.insert(record);
			
			mf.setStatus(1);
		}
		MoodRecord scoreQuery = new MoodRecord();
		scoreQuery.setRecordId("MR" + nowDate);
		records = moodSve.query(scoreQuery);
		Map<Integer, Integer> map = new HashMap<Integer, Integer>();
		for (MoodRecord mr : records) {
			Integer i = map.get(mr.getScore());
			if (i == null) {
				map.put(mr.getScore(), 1);
			} else {
				map.put(mr.getScore(), i + 1);
			}
		}
		
		List<Map<String, String>> ret = new ArrayList<Map<String, String>>();
		for (int i = 1; i < 11; i++) {
			Integer j = map.get(i);
			if (j != null) {
				Map<String, String> test = new HashMap<String, String>();
				if (i == score) {
					test.put("name", i + "分 (您已选)");
				} else {
					test.put("name", i + "分");
				}
				double jr = j.doubleValue();
				double rate = jr / records.size();
				DecimalFormat decimalFormat = new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
				String pr = decimalFormat.format(rate * 100);
				test.put("value", pr);
				ret.add(test);
			} else {
				Map<String, String> test = new HashMap<String, String>();
				test.put("name", i + "分");
				test.put("value", 0 + "");
				ret.add(test);
			}
		}
		mf.setRet(ret);
		mf.setTotalCount(records.size());
		
		List<Integer> dates = drawRecordSve.getDrawDate();
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");  
			Date date = new Date();  
			String str = sdf.format(date);
			boolean show = false;
			for (Integer d : dates) {
				sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String dateStart = str + "-" + d + " 00:00:00";  
				Date startDate;
				startDate = sdf.parse(dateStart);
				String dateEnd = str + "-" + d + " 23:59:59";
				Date endDate = sdf.parse(dateEnd);
				if (startDate.before(date) && endDate.after(date)) {
					show = true;
					break;
				}
			}
			if (show && !StrManager.isEmpty(userId)) {
				mf.setCanDraw(1);
			} else if (show && StrManager.isEmpty(userId)) {
				mf.setCanDraw(2);
			} else if (!show) {
				mf.setCanDraw(3);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		return new Gson().toJson(mf).toString();
	}
	
	@RequestMapping(value = "/getSystemSetting", produces = "text/html;charset=UTF-8") //避免json中文?乱码
	@ResponseBody
	public String getSystemSetting(HttpServletResponse response) {
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		
		List<ScoreReason> ret = new ArrayList<ScoreReason>();
		
		Map<String, List<String>> lrMap = levelSve.getReasonMap();
		List<LevelScore>lss = levelSve.query(new LevelScore());
		for (LevelScore ls : lss) {
			ScoreReason sr = new ScoreReason();
			sr.setScore(ls.getScore());
			sr.setReasons(lrMap.get(ls.getLevel().name()));
			ret.add(sr);
		}
		
		return new Gson().toJson(ret).toString();
	}
	
	@RequestMapping(value = "/getRule", produces = "text/html;charset=UTF-8") //避免json中文?乱码
	@ResponseBody
	public String getRule(HttpServletResponse response) {
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		
		String ret = moodSve.getRule();
		
		return ret;
	}
}
